package component.firstPage.register;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;
import java.util.Scanner;
import util.ConnectionUtils;

public class _register01 {
    public static void doRegister(){
        Scanner myscanner = new Scanner(System.in);
        Connection connection = null;
        PreparedStatement pstmt = null;

        try {
            System.out.println("请输入要注册用户名 name:");
            String regisName = myscanner.nextLine();

            System.out.println("请输入要注册的用户年龄 age:");
            int regisAge = myscanner.nextInt();
            myscanner.nextLine(); // 处理输入年龄后的换行符

            System.out.println("请输入要注册的账号 account:");
            String regisAccount = myscanner.nextLine();

            String regisPassword;
            while(true) {
                System.out.println("请输入新密码:");
                regisPassword = myscanner.nextLine();
                System.out.println("请重新输入密码:");
                String ensureRegisPassword = myscanner.nextLine();
                if (regisPassword.equals(ensureRegisPassword)) {
                    break;
                } else {
                    System.out.println("密码不一致请重新输入!");
                }
            }

            // 生成用户ID
            String regisId = "U" + String.format("%04d", new Random().nextInt(10000));
            
            connection = ConnectionUtils.getConn();
            String sql = "INSERT INTO user (id, name, age, account, password, user_type) VALUES (?, ?, ?, ?, ?, ?)";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, regisId);
            pstmt.setString(2, regisName);
            pstmt.setInt(3, regisAge);
            pstmt.setString(4, regisAccount);
            pstmt.setString(5, regisPassword);
            pstmt.setInt(6, 1);  // 默认注册为患者用户

            int result = pstmt.executeUpdate();
            if(result > 0) {
                System.out.println("注册成功!");
            } else {
                System.out.println("注册失败，请稍后重试!");
            }

        } catch (SQLException e) {
            System.err.println("注册过程中发生错误: " + e.getMessage());
        } finally {
            ConnectionUtils.close(connection, pstmt, null);
        }
    }
}
